//
//  TabThreeViewController.m
//  DaJiang
//
//  Created by sally on 16/9/24.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "HMSegmentedControl.h"
#import "NewsCell.h"
#import "NewsDetailViewController.h"
#import "TabThreeViewController.h"
#import "UserModel.h"
#import "ChatManager.h"

@interface TabThreeViewController () <IChatManagerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (assign, nonatomic) enum NewsType newsType;
@property (strong, nonatomic) NSMutableArray *tableData;

@end

@implementation TabThreeViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setNotification];
  [self initControl];
  [self initData];
  [self setRefresh];
  
  //来自通知,跳转至聊天页-appdelegate还未给入口，暂不管
  if (self.userInfo) {
    [self gotoNewsDetail];
  }
  
}

- (void)dealloc {
  [self unregisterNotifications];
}

#pragma mark 设置通知
- (void)setNotification {
  [self registerNotifications];
  //重新登录需要刷新会话页。
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadRefreshData) name:KNOTIFICATION_LOGINCHANGE object:nil];
}

#pragma mark 初始化控件
- (void)initControl {
  //[self setNav];
  self.title = @"消息通知";
  [[CommonMethod sharedCommonMethod] setExtraCellLineHidden:self.tableView];
  
  //显示缓冲圈
  [[CommonMethod sharedCommonMethod] createProgressHUDInView:self.view withMessage:@""];
}

#pragma mark 初始化数据
- (void)initData {
  self.tableData = [[NSMutableArray alloc] init];
}

- (void)setRefresh {
  __weak typeof(self) weakSelf = self;
  // 添加下拉刷新列表数据功能
  _tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:weakSelf refreshingAction:@selector(loadRefreshData)];
  
  [self loadRefreshData];
}

#pragma mark - 获取数据
- (void)loadRefreshData {
  [self.tableData removeAllObjects];
  self.tableData = [self loadDataSource];
  [self.tableView reloadData];
  [self.tableView.header endRefreshing];
  //隐藏缓冲圈
  [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}

#pragma mark 获取通讯数据及处理
- (NSMutableArray *)loadDataSource {
  NSMutableArray *ret = nil;
  NSArray *conversations = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
  
  //去空 去无扩展ext
  NSMutableArray *sourceArr = [NSMutableArray array];
  for (EMConversation *conv in conversations) {
    if ([conv latestMessage]) {//&&[conv latestMessage].ext
      [sourceArr addObject:conv];
    }
  }
  //排序
  NSArray *sorte = [sourceArr sortedArrayUsingComparator:
                    ^(EMConversation *obj1, EMConversation *obj2) {
                      EMMessage *message1 = [obj1 latestMessage];
                      EMMessage *message2 = [obj2 latestMessage];
                      if (message1.timestamp > message2.timestamp) {
                        return (NSComparisonResult) NSOrderedAscending;
                      } else {
                        return (NSComparisonResult) NSOrderedDescending;
                      }
                    }];
  
  ret = [[NSMutableArray alloc] initWithArray:sorte];
  return ret;
}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return self.tableData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
  return cell.frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  NewsCell *cell = (NewsCell *) [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
  if (!cell) {
    cell = [[[NSBundle mainBundle] loadNibNamed:@"NewsCell" owner:nil options:nil] lastObject];
  }
  
  cell.cellConvData = [self.tableData objectAtIndex:indexPath.row];
  return cell;
}

#pragma mark TableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES]; //返回后选中状态消失
  EMConversation *conversation = [self.tableData objectAtIndex:indexPath.row];
  NewsDetailViewController *vc = [[NewsDetailViewController alloc] init];
  vc.conversation = conversation;
  vc.hidesBottomBarWhenPushed = YES;
  [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - EMChatManagerChatDelegate
#pragma mark 消息未读数变化回调
- (void)didUnreadMessagesCountChanged {
  [self loadRefreshData];
}

#pragma mark 收到在线消息时的回调
- (void)didReceiveMessage:(EMMessage *)message {
  [self loadRefreshData];
}

#pragma mark 接收到离线非透传消息的回调
- (void)didReceiveOfflineMessages:(NSArray *)offlineMessages {
  [self loadRefreshData];
}

#pragma mark 发送消息后的回调
- (void)didSendMessage:(EMMessage *)message error:(EMError *)error {
  [self loadRefreshData];
}

#pragma mark - 私有方法
#pragma mark 跳转聊天页
- (void)gotoNewsDetail {
  NSString *chatter = [_userInfo valueForKey:EaseMobChatterKey];
  EMConversation *conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:chatter conversationType:eConversationTypeChat];
  NewsDetailViewController *newDetailVC = [[NewsDetailViewController alloc] init];
  newDetailVC.conversation = conversation;
  newDetailVC.hidesBottomBarWhenPushed = YES;
  [self.navigationController pushViewController:newDetailVC animated:YES];
}

#pragma mark 设置导航栏
- (void)setNav {
  //通知的需求已经去掉，关于通知的都可以去掉
  HMSegmentedControl *segmCtrl = [[HMSegmentedControl alloc] initWithSectionTitles:@[ @"消息 ", @"通知 " ]];
  [OperationManager configSegment:segmCtrl type:SegmentedType_News];
  [segmCtrl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
  self.navigationItem.titleView = segmCtrl;
}

#pragma mark 切换segment控件响应动作
- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl {
  [self switchSegment:segmentedControl.selectedSegmentIndex];
}

- (void)switchSegment:(NSInteger)index {
  self.newsType = index;
  NSLog(@"%lu", (unsigned long) self.newsType);
}

#pragma mark 注册delegate
- (void)registerNotifications {
  [self unregisterNotifications];
  [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
}

- (void)unregisterNotifications {
  [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

@end
